from pydantic import BaseModel, Field
import threading
import time

class ServerNode(BaseModel):
    """Node protocol consists of url and status."""
    url: str
    desc: str
    model_name: str
class SessionManager(BaseModel):
    """Session state protocol consists of session_id, session_state, and session_history."""
    session_start_time: dict = Field(default_factory=dict)
    session_timers: dict = Field(default_factory=dict)
    function: object

    def __init__(self, session_id: int, function):
        self.session_start_time = dict()
        self.function = function
    
    def create_session(self, session_id: int):
        if self.session_timers[session_id] is None:
            self.session_timers[session_id] = threading.Timer(60*30, self.clear_session(session_id), session_id)
        else:
            self.session_timers[session_id].cancel()

        self.session_start_time[session_id] = time.time()
        self.session_timers[session_id].start()
    def clear_session(self, session_id: int):        
        self.function(session_id)
        del self.session_start_time[session_id]
    

class ServerNodeStatus(ServerNode):
    alive: bool = Field(default=False)
    user_sessions: dict = Field(default_factory=dict)

